package com.qf.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.constant.RedisConstant;
import com.qf.dao.SetMealDao;
import com.qf.entity.PageResult;
import com.qf.entity.QueryPageBean;
import com.qf.pojo.Setmeal;
import com.qf.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhouhao
 * @create 2021-12-22 20:07
 */
@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private JedisPool jedisPool;
    //添加套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐
        setMealDao.add(setmeal);
        //添加套餐中关联的检查组
        Integer setmealId = setmeal.getId();
        for (Integer checkgroupId : checkgroupIds){
            HashMap<String, Object> map = new HashMap<>();
            map.put("setmealId",setmealId);
            map.put("checkgroupId",checkgroupId);
            setMealDao.addSetmealAndCheckGroupBySetmealId(map);
        }
        //将图片名称保存到redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
    }

    //分页查询套餐
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //开启分页
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //获取查询条件
        String queryString = queryPageBean.getQueryString();
        //根据条件查询
        List<Setmeal> setmealList =  setMealDao.findByCondition(queryString);
        //对查询结果进行分页
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealList);
        long total = pageInfo.getTotal();
        List<Setmeal> list = pageInfo.getList();
        return new PageResult(total,list);
    }

    //查询所有套餐
    @Override
    public List<Setmeal> getAllSetMeal() {
        return setMealDao.getAllSetMeal();
    }

    //根据id查询套餐的详细信息
    @Override
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }

    //获取套餐统计数据
    @Override
    public Map<String,Object> getSetmealReport() {
        List<Map<String,Object>> list = setMealDao.findSetmealAndCount();
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealCount",list);
        ArrayList<String> names = new ArrayList<>();
        for (Map<String,Object> m : list){
            String name = (String)m.get("name");
            names.add(name);
        }
        map.put("setmealNames",names);
        return map;
    }
}
